<?php
defined('ENV') || exit('illegal Access! @110');
class Route
{
	public static $path = '';

	public static $ismatch = false;
	public static $PathMatchName = false;
	public static $PathMatchInfo = array();

	public static $module = '';
	public static $controller = '';
	public static $action = '';

	public static $pathRouter = array();

	public static $args = array();

	public static $error = '';

	public function __construct()
	{}

	//解析请求路径
	public static function parseURI($path)
	{
		self::$path = $path;
		self::$pathRouter = RouteConfig::$Path;
		
		if (empty($path)) {
            self::$module     = RouteConfig::$defaultModule;
            self::$controller = RouteConfig::$defaultCtrl;
            self::$action     = RouteConfig::$defaultAction;
            
            self::$PathMatchInfo = [self::$module, self::$controller, self::$action];
            return;
        }

		//检查uri路由, 只检查正则路由
        if (!empty(self::$pathRouter) && !empty(self::$path)) {
            self::pregParse(self::$pathRouter, self::$path);
    
            if (!empty(self::$PathMatchInfo)) {
                $routeInfo = self::$PathMatchInfo;
                self::$module     = $routeInfo['moduleName'];
                self::$controller = $routeInfo['controllerName'];
                self::$action     = $routeInfo['actionName'];
                self::$args       = $routeInfo['args'];
            } else {
                Response::error('抱歉，未找到匹配的处理方法！');
            }
        }
	}

	//正则匹配分析
    //1. 待匹配的字符串跟配置文件中数组的某一个键完全一样
    //2. 没有完全一样的就挨个跟数组的键进行匹配
	public static function pregParse($router, $subject)
	{
		$matchRoute = false;
		$path = '';
		if (!empty($router[$subject])) {
            $matchRoute = $subject;
			$path = $router[$subject]; //单纯的字符串, 没有正则表达式
		} else {
			foreach ($router as $pattern => $route) {

				$countMatched= preg_match('#^'.$pattern.'$#', $subject, $matches);
				
				if ($countMatched == 0) {
				    continue;
                }

                self::$ismatch = true;
                $matchRoute = $pattern;
                // "abc_123_456_789" => "$1/$2/$3/id/$4"
                // 变成 "abc/123/456/id/789"
                foreach ($matches as $key => $value) {
                    $route = str_replace('$'.$key, $value, $route);
                }

                $path = $route;
                
                break;
			}
		}
		
		if (!empty($path)) {
            self::$PathMatchName = $matchRoute;
            self::$PathMatchInfo = self::analysisPath($path);
        } else {
		    $path = RouteConfig::$defaultModule.'/'.RouteConfig::$defaultCtrl.'/'.RouteConfig::$defaultAction;
            self::$PathMatchInfo = self::analysisPath($path);
		    //return array();
        }
	}

	//分析路径参数
	public static function analysisPath($path)
	{
        $moduleName     = RouteConfig::$defaultModule;
        $controllerName = RouteConfig::$defaultCtrl;
        $actionName     = RouteConfig::$defaultAction;
	    $args = array();
	    
		//获得module/controller/action
		$arrPathInfo = explode('/', $path);//存放URL中以正斜线隔开的内容的数组
		!empty($arrPathInfo[0]) && ($moduleName = $arrPathInfo[0]);
		!empty($arrPathInfo[1]) && ($controllerName = $arrPathInfo[1]);
		!empty($arrPathInfo[2]) && ($actionName = $arrPathInfo[2]);

		//检查安全性
//		try {
//			Verify::check('module', $moduleName, 'module:ctrl:action');
//			Verify::check('ctrl', $controllerName, 'module:ctrl:action');
//			Verify::check('action', $actionName, 'module:ctrl:action');
//		} catch (Exception $e) {
//            Response::error($e->getMessage());
//        }

		//存放除module/controller/action之外的参数
		// /a/1/b/2/c/3 ==> ?a=1&b=2&c=3
		// 当键和值不成对出现时,默认最后一个键的值为0
		// 参数中不要出现数字键,否则在合并post,get参数时会出错
		if (count($arrPathInfo) > 3) {
			$arrPath = array_slice($arrPathInfo, 3);
			$intArgNum = count($arrPath);
			if ($intArgNum % 2 != 0) {
				$arrPath[] = '';//最后补一个''
			}

			for ($i=0; $i<$intArgNum; $i=$i+2) {
				$args[$arrPath[$i]] = $arrPath[$i+1];
			}
		}
		
		return array(
            'moduleName'     => $moduleName,
            'controllerName' => $controllerName,
            'actionName'     => $actionName,
            'args'           => $args
        );
	}

	public static function debug()
    {
        echo '<pre>';
        print_r([
            'MatchName' => self::$PathMatchName,
            'MatchInfo' => self::$PathMatchInfo,
        ]);
        exit();
    }

}